﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using System.Windows;
namespace FinosLibrary {
    public class Logic:NotifyProperty {
        private static Dictionary<string, Dictionary<string, Invoker>> logicMap = new Dictionary<string, Dictionary<string, Invoker>>();
        public string app;
        public SynchronizationContext syn;
        public static void doLogic(string fun, object b) {
            doLogic(new Package(fun, b));
        }
        public static void doLogic(string fun) {
            doLogic(new Package(fun));
        }
        public static void doLogic(Package p) {
            doLogic(p, "");
        }
        public static void doLogic(Package p, string appname) {
            if (!logicMap[appname].ContainsKey(p.head)) return;
            Invoker Invoker = logicMap[appname][p.head];
            Invoker.SetArg(p);
            Logic o = Invoker.obj as Logic;
            if (o.syn != null) {
                o.syn.Post(_doLogic, Invoker);
            } else {
                _doLogic(Invoker);
            }
        }
        public static void _doLogic(object arg) {
            Invoker Arg = arg as Invoker;
            Arg.Invoke();
        }
        public Logic() {
            syn = SynchronizationContext.Current;
            MessageProcessAttribute[] mpas = GetType().GetCustomAttributes(typeof(MessageProcessAttribute), true) as MessageProcessAttribute[];
            if (mpas.Length == 0) return;
            MessageProcessAttribute mpa = mpas[0];
            app = mpa.appName;
            if (!logicMap.ContainsKey(app)) {
                logicMap[app] = new Dictionary<string, Invoker>();
            }
            LogicParse.Parse(this, logicMap[app]);
        }
    }
}
